package com.changgou.file.controller;



import com.changgou.file.FastDFSFile;
import com.changgou.file.util.FastDFSClient;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


/**
 * @author 1
 * @data 2022/1/9
 */
@RestController
public class UploadController {


    /**
     * 图片上传
     *
     * @param file 前端传过来的图片的内容
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file){
        try {
            //获取字节数组
            byte[] bytes = file.getBytes();
            //获取源文件的扩展名
            String fileName = StringUtils.getFilenameExtension(file.getOriginalFilename());

            //将获取到的文件名和文件的扩展名还有字节数组分装到pojo中
            FastDFSFile dfsFile = new FastDFSFile(file.getOriginalFilename(),bytes,fileName);
            //使用工具类调用方法
            //[0]-->group1
            //[1]-->M00/00/00/wKjThGHamy2AM5DxAAHZWN2b9fs955.jpg
            //访问路径：http://192.168.211.132:8080/group1/M00/00/00/wKjThGHamy2AM5DxAAHZWN2b9fs955.jpg
            String[] upload = FastDFSClient.upload(dfsFile);

            //拼接图片的访问路径返回到前端用于回显图片
            String realPath = "http://192.168.211.132:8080/"+upload[0] +"/"+upload[1];
            return realPath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
